<?php

namespace CNEPAdmin\Controller;

use CNEPAdmin\Controller\CommonController;
use JPush\Model as M;
use JPush\JPushClient;
use JPush\Exception\APIRequestException;
use JPush\Exception\APIConnectionException;

class MessageController extends CommonController {

    protected $_modelName = "Message";

    protected function setCode() {
        $this->_code = "System";
    }

    /**
     * 得到条件查询数组
     * @return Array
     */
    protected function _getQueryArr(&$where, &$order) {

        if (strlen(trim(I("sTitle"))) > 0) {
            $where['title'] = array('like', "%" . trim(I("sTitle", '')) . '%');
        }
        if (intval(trim(I("sIsSend", -1))) >= 0) {
            $where['isSend'] = I("sIsSend");
        }
        if (intval(trim(I("sType", -1))) >= 0) {
        	$where['messageType'] = I("sType");
        }

        $where['isOn'] = 1;

        $orderBy = 'addTime';
        $desc = 'desc';
        if (intval(I("sDesc")) === 1) {
            $desc = 'asc';
        }
        if (strlen(trim(I("sOrderBy", ''))) > 0) {
            $orderBy = I("sOrderBy");
        }

        $order = array(
            $orderBy => $desc
        );
		//dump($where);
        return $where;
    }

    /**
     * 查看列表
     */
    public function index() {
        $this->checkPriv('msg', 1, false); // 权限

        $this->_getOnePageData("getMessageList", "getMessageListLength");
    }

    public function messageMsg() {
        $this->checkPriv('msg', 1, false);
        $rt = true;
        $id = intval(I("messageID", 0));

        if ($id > 0) { // 编辑
            $arr = D("Message")->getMessage($id);
            if ($arr) {
            	!empty($arr['img'])?$arr['img']=C("IMG_DOMAIN").$arr['img']:"";
            	!empty($arr['img2'])?$arr['img2']=C("IMG_DOMAIN").$arr['img2']:"";
                $arr['addTime'] = date("Y/m/d H:i:s", $arr['addTime']);
				$regiontext = '';
				$m_r = M('Message_region')->where("messageID=$id")->select();
				if(!empty($m_r)){
					foreach($m_r AS $key=>$value){
						if($value!=end($m_r)){
							$regiontext .= $value['regionID'] . ',';
						} else {
							$regiontext .= $value['regionID'];
						}
					}
				}
				$arr['regiontext'] = $regiontext;
                unset($arr['isOn']);
            }
        } else {
            $error = "无效ID";
            $rt = false;
        }

        $this->ajaxReturn(array('result' => $rt, 'desc' => $error, 'arr' => $arr));
    }

    public function saveMessage() {
        $this->checkPriv("msg", 2);
        $msgID = intval(I("post.messageID"));
        $adminArr = $_SESSION['adminArr'];

        if ($adminArr) {
            $_POST['authorID'] = $adminArr['adminID'];
            $_POST['author'] = $adminArr['account'];
            $_POST['authorFrom'] = 0;
            !empty($_POST['img'])?$_POST['img']=$this->get_url_path(I('post.img')):"";
            !empty($_POST['img2'])?$_POST['img2']=$this->get_url_path(I('post.img2')):"";
            
            D()->startTrans();

			$rt=true;
			$rt1=true;
			$rt2=true;
            if ($msgID > 0) {
                $rt = $this->_updateMessage($msgID);
				$rt1 = M('Message_region')->where("messageID=$msgID")->delete();
				$regions = explode(",",$_POST['regiontext']);
				
				$data['messageID'] = intval($msgID);
				foreach($regions AS $key=>$value){
					$data['regionID'] = $value;
					$rt2 = M('Message_region')->add($data);
				}
            } else {
                $rt = $this->_addMessage();
				
				$regions = explode(",",$_POST['regiontext']);
				$data['messageID'] = intval($rt);
				foreach($regions AS $key=>$value){
					$data['regionID'] = $value;
					$rt1 = M('Message_region')->add($data);
				}

                if (intval(I("post.isSend")) === 1 && $rt !== false) {
                    // 推送消息
                    $rt = $this->_sendMsgToUser($_POST['title'], '你有一条新信息，请查收',array("action"=>"open-message","messageID"=>$rt));
//                    dump($rt->isOk);
                    
                    if (!$rt->isOk) {
                        $this->_error = '发送推送信息失败';
                    } else {
                        $rt = TRUE;
                    }
                }
            }

            if ($rt !== false && $rt1 !== false && $rt2 !== false)
                D()->commit();
            else
                D()->rollback();

            $this->ajaxReturn(array(
                'result'=>$rt,
                'desc' => $this->_error
            ));
        } else {
            $this->_error = "登陆失效，请重新登录";
            $this->_myAjaxReturn(false);
        }
    }

    private function _addMessage() {
        $this->_setModel();
        if($_POST['shopID']) {
            $shopArr = D("Shop")->where('shopID = ' . $_POST['shopID'])->field('shopType')->find();
            $_POST['shopType'] = $shopArr['shopType'];
        }
        $rt = $this->_model->addMessage($_POST);
        return $rt;
    }


    /**
     * 推送
     */
    private function _sendMsgToUser($msg, $title, $extras = array()) {
        vendor('JPush/autoload');//JPushClient   notification  APIRequestException APIConnectionException
        //$client = new JPushClient('0335dd3eb505909bdc492d06', 'f9f8e4b165b9448fc0fd0539');   //测试key
		  $client = new JPushClient('161f1017deaf5dc1cba3e83d', 'bb3a91fe849af6cb1d754db9');   //生产key
        try {
            $result = $client->push()
                    ->setPlatform( M\all )
                    //->setAudience( M\all)
					->setAudience(M\audience(M\tag(array('test'))))
                    ->setNotification( 
                        M\notification($msg, 
                        M\ios($msg, "happy", "+1", true, $extras, "Ios8 Category"),
                        M\android($msg, $title, 1, $extras)
                    ))
                    ->setMessage(M\message('Message Content', 'Message Title', 'Message Type', array("key1" => "value1", "key2" => "value2")))
                    //->printJSON()
                    ->send();
					
            return $result;
        } catch (APIRequestException $e) {
			
            return false;
        } catch (APIConnectionException $e) {
			
            return false;
        }
    }

    /**
     * 更新基本信息(需要更新什么就提交什么)
     */
    private function _updateMessage($msgID) {

        $rt = FALSE;

        if ($msgID > 0) {
            // 判断是否已删除
            $model = D("Message");
            $arr = $model->where("messageID=$msgID")->find(array('isOn', 'isSend'));
            if (intval($arr['isOn']) === 1) {
                $isSend = '';
                if (intval($arr['isSend']) === 1) { // 如果已经发送了,不可修改发送状态
                    $_POST['isSend'] = 1;
                    $isSend = 0; // 不推送
                } else if (intval($_POST['isSend']) === 1) {
                    $isSend = 1; // 推送
                }
                // 未删除的话修改
                if($_POST['shopID']) {
                    $shopArr = D("Shop")->where('shopID = ' . $_POST['shopID'])->field('shopType')->find();
                    $_POST['shopType'] = $shopArr['shopType'];
                }
                $rt = $model->updateMessage($_POST);

                if ($rt !== false && $isSend === 1) {
                    // 如果更新成功且选择推送
                    $rt = $this->_sendMsgToUser($_POST['title'], '你有一条新信息，请查收',array("action"=>"open-message","messageID"=>$msgID));
                    
                    if (!$rt->isOk) {
                        $this->_error = '发送推送信息失败';
                    } else {
                        $rt = TRUE;
                    }
                } elseif ($rt === false) {
                    $this->_error = '更新消息失败';
                }
            } else {
                $this->_error = "消息不存在";
            }
        } else {
            $this->_error = "无效ID";
        }
        return $rt;
    }

    /**
     * 删除
     */
    public function deleteMessage() {
        $this->checkPriv("msg", 2);

        $msgID = intval(I("post.messageID"));

        if ($msgID > 0) {
            $this->_ajaxOperate('deleteMessage', '', '', $msgID);
        } else {
            $this->ajaxReturn(array(
                "result" => 0, "desc" => "无效ID"
            ));
        }
    }
	
	public function test(){
		$rt = $this->_sendMsgToUser('测试', '你有一条新信息，请查收',array("action"=>"open-message","messageID"=>1));
		var_dump($rt);
	}

}
